package com.prayerdiary.app;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.prayerdiary.adapters.OfferedQazaAdapter;
import com.prayerdiary.app.R;
import com.prayerdiary.database.PrayerDiaryDBHelper;
import com.prayerdiary.model.DailyPrayer;
import com.prayerdiary.utils.DeleteBtnVisibilityListener;
import com.prayerdiary.utils.Notifier;
import com.prayerdiary.utils.PDProgressDialog;
import com.prayerdiary.utils.Utils;

public class OfferedQazaActivity extends Activity implements Notifier, OnClickListener, DeleteBtnVisibilityListener
{
	private OfferedQazaAdapter adapter = null;

	private ArrayList<DailyPrayer> prayerList = null;

	private View visibileDelBtnRow = null;

	private Date qazaDayDate;

	private static boolean isSearchMode = false;

	private static boolean isEditMode = false;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

		setContentView(R.layout.offered_qaza);

		ListView list = (ListView) findViewById(R.id.show_offered_qaza_lv);
		PrayerDiaryDBHelper dbHelper = new PrayerDiaryDBHelper(this);
		prayerList = dbHelper.getQazaPrayerRecord();
		adapter = new OfferedQazaAdapter(this, dbHelper.getQazaPrayerRecord());
		// adapter = new OfferedQazaAdapter(this, prayerList);
		list.setAdapter(adapter);
		adapter.setNofitier(this);
		adapter.setDeleteBtnVisibilityListener(this);

		PDProgressDialog.getInstanse().hideDialog();
		addButtonListeners();
	}

	private void addButtonListeners()
	{
		ImageButton editBtn = (ImageButton) findViewById(R.id.pdh_edit_btn);
		editBtn.setOnClickListener(this);

		ImageButton doneBtn = (ImageButton) findViewById(R.id.pdh_done_btn);
		doneBtn.setOnClickListener(this);

		ImageButton headerSearchBtn = (ImageButton) findViewById(R.id.pdh_search_btn);
		headerSearchBtn.setOnClickListener(this);

		ImageView searchBtn = (ImageView) findViewById(R.id.sb_search_iv);
		searchBtn.setOnClickListener(this);

		ImageView cutBtn = (ImageView) findViewById(R.id.sb_cut_iv);
		cutBtn.setOnClickListener(this);

		ImageView selectDateBtn = (ImageView) findViewById(R.id.sb_calendar_iv);
		selectDateBtn.setOnClickListener(this);
	}

	Runnable populate = new Runnable()
	{
		@Override
		public void run()
		{
			// FIXME the first time search operation is performed then on
			// adapter.clear the prayerlist is also cleared. After the first
			// time the prayerlist is never cleared with adapter.clear
			adapter.clear();
			adapter.addAll(prayerList);
			adapter.notifyDataSetChanged();
		}
	};

	Runnable populateEdit = new Runnable()
	{
		@Override
		public void run()
		{
			adapter.clear();
			for (int i = 0; i < prayerList.size(); i++)
			{
				DailyPrayer prayer = prayerList.get(i);
				prayer.setEditMode(true);
				adapter.add(prayer);
			}
			adapter.notifyDataSetChanged();
		}
	};

	@Override
	public void onClick(View v)
	{
		if (v.getId() == R.id.pdh_search_btn)
		{
			View searchBar = findViewById(R.id.soq_search_bar);
			if (searchBar.isShown())
			{
				searchBar.setVisibility(View.GONE);
				isSearchMode = false;
				refreshData(isEditMode);
			}
			else
			{
				searchBar.setVisibility(View.VISIBLE);
			}
		}
		else if (v.getId() == R.id.pdh_edit_btn)
		{
			ImageButton editBtn = (ImageButton) findViewById(R.id.pdh_edit_btn);
			editBtn.setVisibility(View.GONE);
			ImageButton doneBtn = (ImageButton) findViewById(R.id.pdh_done_btn);
			doneBtn.setVisibility(View.VISIBLE);
			for (int i = 0; i < prayerList.size(); i++)
			{
				((DailyPrayer) prayerList.get(i)).setEditMode(true);
			}
			isEditMode = true;
			// Adapter is not containing the prayerList. Setting
			// prayerList elements to edit more wont have any change. Therefore,
			// we have to clear adapter and add the prayerList to it
			adapter.clear();
			adapter.addAll(prayerList);
			adapter.notifyDataSetChanged();
		}
		else if (v.getId() == R.id.pdh_done_btn)
		{
			ImageButton editBtn = (ImageButton) findViewById(R.id.pdh_edit_btn);
			editBtn.setVisibility(View.VISIBLE);
			ImageButton doneBtn = (ImageButton) findViewById(R.id.pdh_done_btn);
			doneBtn.setVisibility(View.GONE);
			isEditMode = false;
			for (int i = 0; i < prayerList.size(); i++)
			{
				((DailyPrayer) prayerList.get(i)).setEditMode(false);
			}
			adapter.notifyDataSetChanged();
		}
		else if (v.getId() == R.id.sb_cut_iv)
		{
			EditText searchText = (EditText) findViewById(R.id.sb_search_et);
			searchText.setText("");
			isSearchMode = false;
			refreshData(isEditMode);
		}
		else if (v.getId() == R.id.sb_calendar_iv)
		{
			showDatePickerDialog();
		}
		else if (v.getId() == R.id.sb_search_iv)
		{
			// FIXME
			Utils u = new Utils();
			long longDate = (qazaDayDate == null ? 0 : qazaDayDate.getTime());
			if (longDate == 0)
			{
				u.showMessage("Error", "Please try again", this).run();
				isSearchMode = false;
			}
			else
			{
				PrayerDiaryDBHelper db = new PrayerDiaryDBHelper(this);
				DailyPrayer prayer = db.searchQazaPrayerRecord(longDate);
				if (prayer == null)
				{
					u.showMessage("Sorry", "No prayer record found for this date", this).run();
					isSearchMode = false;
				}
				else
				{
					isSearchMode = true;
					prayerList.clear();
					prayerList.add(prayer);
					refreshData(isEditMode);
				}
			}
		}
	}

	@Override
	public void notify(Object data, String type)
	{
		DailyPrayer prayer = (DailyPrayer) data;
		PrayerDiaryDBHelper db = new PrayerDiaryDBHelper(this);

		if ("DEL".equalsIgnoreCase(type))
		{
			if (db.deleteQazaPrayerRecord(prayer))
			{
				CharSequence msg = "Record Deleted";
				Toast.makeText(OfferedQazaActivity.this, msg, Toast.LENGTH_SHORT).show();
				refreshData(true);
			}
			else
			{
				CharSequence msg = "Sorry! Error while deleting record";
				Toast.makeText(OfferedQazaActivity.this, msg, Toast.LENGTH_SHORT).show();
			}
		}
		else
		{
			Utils.println("Updating daily prayer" + type);
			boolean updated = db.updateQazaPrayer(prayer);
			if (updated)
			{
				refreshData(false);
			}
			else
			{
				CharSequence msg = "Sorry! Error while updating";
				Toast.makeText(OfferedQazaActivity.this, msg, Toast.LENGTH_SHORT).show();
				refreshData(false);
			}
		}
	}

	/**
	 * Retrieves the prayer list from the database
	 * <p>
	 * calls the populate method to update the gui
	 * <p>
	 * if the search bar is open then the prayer list is not retrieved from the
	 * database
	 * */
	private void refreshData(boolean editMode)
	{
		PrayerDiaryDBHelper dbHelper = new PrayerDiaryDBHelper(this);
		if (!isSearchMode)
		{
			prayerList = dbHelper.getQazaPrayerRecord();
		}
		if (editMode)
		{
			runOnUiThread(populateEdit); // Populate the edit list and set the
											// fields editable
		}
		else
		{
			runOnUiThread(populate);
		}
	}

	/**
	 * Display the date picker dialog and set the search text to the selected
	 * date
	 */
	private void showDatePickerDialog()
	{
		final Calendar c = Calendar.getInstance();
		int mYear = c.get(Calendar.YEAR);
		int mMonth = c.get(Calendar.MONTH);
		int mDay = c.get(Calendar.DAY_OF_MONTH);

		DatePickerDialog dpd = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener()
		{
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
			{
				Calendar calendar = Calendar.getInstance();
				calendar.clear();
				calendar.set(year, (monthOfYear), dayOfMonth, 0, 0, 0);
				qazaDayDate = calendar.getTime();
				EditText date = (EditText) findViewById(R.id.sb_search_et);
				date.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
			}
		}, mYear, mMonth, mDay);
		dpd.show();
	}

	@Override
	public void setDelBtnVisible(boolean visible)
	{
		if (!visible && visibileDelBtnRow != null)
		{
			ImageButton deleteBtn = (ImageButton) visibileDelBtnRow.findViewById(R.id.oqi_delete_button);
			deleteBtn.setVisibility(View.GONE);
			visibileDelBtnRow = null;
		}
	}

	@Override
	public void setVisibleBtnRow(View row)
	{
		visibileDelBtnRow = row;
	}

}